<?php
require $_SERVER['DOCUMENT_ROOT'].'/nsbbs/conf/app.config.php';
session_start();
Class Db
{
	private $_link;
	private static $_instance = null;
	private function __construct(){
		$this->_link = @mysqli_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME,DB_PORT);
		if(mysqli_connect_errno()){
			$this->writelog('数据库连接错误:'.mysqli_connect_error());
		}
	}
	//禁止克隆
	private function __clone(){}

	//创建唯一实例
	public static function getInstance (){
		if(!self::$_instance){
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	//log写入
	private function writelog($err){
		$err_time = date('Y-m-d H:i:s');
		$fd = fopen(LOG_PATH.'/err.log', 'a');
		fwrite($fd, "{$err}==时间：{$err_time}\n");
		fclose($fd);
	}
    //后台红点
    private function getReDot($userid){
        $gzwx_sign = $this->getSign('gzwx',$userid);
        $hdsb_sign = $this->getSign('hdsb',$userid);
        $all_sign = $gzwx_sign || $hdsb_sign;
        return [gzwx=>$gzwx_sign,hdsb=>$hdsb_sign,all=>$all_sign];
	   
    }
    private function getSign($table,$userid){
        $_data =  $this->find([
    		table => [$table=>'a',content=>'b',module=>'c'],
    		field => 'c.id',
    		where => "a.cid=b.id and b.mid=c.id and a.is_deal=0 and b.delete_time is NULL"
    	]);
    	$_count = count($_data);
    	$_mid = $_data[0]['id'];
    	$_json = $this->find([
    		table => ['module'],
    		field => 'manager',
    		where => "id={$_mid}"
    	])[0]['manager'];
    	$_uids = json_decode($_json);
    	$_index = array_search($userid, $_uids->uids);
    	if($_count && is_numeric($_index)){
    	    return true;
    	}
    	return false;
    }
	//是否登录
	public function islogin(){
		$data = $this->find([
			table => ['bbs_user'],
			where => "`user` = '{$_SESSION['user']}' and `pwd` = '{$_SESSION['pwd']}'"
		]);
		if($data[0]){
		    $data[0]['state'] = $this->getReDot($data[0]['id']);
		    $news = $this->count([
    			table => ['mail'],
    			where => "`to_id` = {$data[0]['id']} and `is_read` = 0"
    		]);
    		
    		$data[0]['news'] = $news>0 ? true:false;
			//登录刷新时间 30分钟更新一次
			$map = [];
			$diff_time = time() - $data[0]['last_time'];
			if(date('Y-m-d',$data[0]['last_time']) < date('Y-m-d')){
				$map['today_lv'] = 5;
				$map['lv'] = '#lv+5#';
			}
			if($diff_time > 1800){
				$map['last_time'] = time();
				$this->update([
					table => 'bbs_user',
					map => $map,
					where => "`id` = {$data[0]['id']}"
				]);
			}

		}
		return $data[0];
	}

	//是否登录
	public function isadmin(){

		$data = $this->find([
			table => ['bbs_manager'],
			where => "md5(user) = '{$_COOKIE['M_']}' and `pwd` = '{$_COOKIE['_W']}'"
		]);
		return $data[0];
	}

	//实例化html
	public function tohtml($data){
		if(is_string($data) || is_numeric($data)){
			$str=htmlspecialchars($data);
			$oStr=[" ","\t","\r\n","\n"];
			$nStr=["&nbsp;","&nbsp;&nbsp;&nbsp;&nbsp;","<br>","<br>"];
			return str_replace($oStr, $nStr, $str);
		}else if(is_array($data)){
	        foreach ($data as $k=>$v){
	            $data[$k] = $this->tohtml($v);          
	        }
	        return $data;
	    }
	}
	
	/* 数据库操作方法 */

	//原生mysql
	public function query($query){
		$result = @mysqli_query($this->_link,$query);
		$data = @mysqli_fetch_all($result,MYSQLI_ASSOC);
		if(mysqli_errno($this->_link)){
			$this->writelog('原生数据查询错误:'.mysqli_error($this->_link));
		}
		return $data;
	}


	// 查询数据库 (参数: table,field,where)

	public function find(array $options){
		$table = $options['table'];
		if(!is_array($table)){
			exit('find的table参数必须是数组');
		}elseif(count($table) >= 2){
			foreach ($table as $key => $value) {
				$tables .= $key." AS $value,";
			}
			$tables = trim($tables,',');
		}else{
			$tables = $table[0];
		}
		$field = $options['field'] ? $options['field'] : '*';
		$where = $options['where'] ? $options['where'] : 1;
		$result = @mysqli_query($this->_link,"SELECT $field FROM $tables WHERE $where");
		$data = @mysqli_fetch_all($result,MYSQLI_ASSOC);
		if(mysqli_errno($this->_link)){
			$this->writelog('数据查询错误:'.mysqli_error($this->_link));
		}
		return $data;
	}

	//插入数据 (参数: table,map) #原样输出#

	public function save(array $options){
		$map = $options['map'];
		if(!is_array($map)){
			exit('map参数必须是数组');
		}
		foreach ($map as $key => $val) {
			$field .= $key.',';
			if(preg_match_all('/^#(.*)#$/', $val,$match)){
				$value .= $match[1][0].',';
			}else{
				$value .= "'$val'".',';
			}
		}
		$field = trim($field,',');
		$value = trim($value,',');
		$table = $options['table'];
		@mysqli_query($this->_link,"INSERT INTO `$table` ($field) VALUES ($value)");
	
		if(mysqli_errno($this->_link)){
			$this->writelog('数据存储错误:'.mysqli_error($this->_link));
		}
		if(mysqli_affected_rows($this->_link) > 0){
			return true;
		}else{
			return false;
		}
	}

	//修改数据 (参数: table,map,where)

	public function update(array $options){
		$where = $options['where'];
		$map = $options['map'];
		if(!$where){
			exit('where参数不能是空');
		}elseif(!is_array($map)){
			exit('map参数必须是数组');
		}
		$table = $options['table'];
		foreach ($map as $key => $val) {
			if(preg_match_all('/^#(.*)#$/', $val,$match)){
				$value .= "$key={$match[1][0]}".',';
			}else{
				$value .= "$key='$val'".',';
			}
			
		}
		$value = trim($value,',');
		@mysqli_query($this->_link,"UPDATE `$table` SET $value WHERE $where");
		
		if(mysqli_errno($this->_link)){
			$this->writelog('数据修改错误:'.mysqli_error($this->_link));
		}
		if(mysqli_affected_rows($this->_link) >= 0){
			return true;
		}else{
			return false;
		}	
	}


	/*删除数据 true为真删除,false为软删除 默认为false
	 *(软删除必须先为表添加delete_time字段,Datetime类型,默认为NULL)
	 *(参数: table,where,[flag])
	*/

	public function remove(array $options){
		$where = $options['where'];
		if(!$where){
			exit('where参数不能是空');
		}
		$table = $options['table'];
		$flag = $options['flag'] ? $options['flag'] : false;
		if($flag){
			@mysqli_query($this->_link,"DELETE FROM `$table` WHERE $where");
		}else{
			$delete_time = date('Y-m-d H:i:s');
			@mysqli_query($this->_link,"UPDATE `$table` SET `delete_time`='$delete_time' WHERE $where");
		}
		if(mysqli_errno($this->_link)){
			$this->writelog('数据删除错误:'.mysqli_error($this->_link));
		}
		if(mysqli_affected_rows($this->_link) >= 0){
			return true;
		}else{
			return false;
		}
	}

	//转义数据

	public function escape($data){
		if(is_string($data)){
	        return mysqli_real_escape_string($this->_link, $data);
	    }else if(is_array($data)){
	        foreach ($data as $k=>$v){
	            $data[$k]=$this->escape($v);          
	        }
	        return $data;
	    }
	}

	//获取num
	public function count(array $options){
		$table = $options['table'];
		if(!is_array($table)){
			exit('count的table参数必须是数组');
		}elseif(count($table) >= 2){
			foreach ($table as $key => $value) {
				$tables .= $key." AS $value,";
			}
			$tables = trim($tables,',');
		}else{
			$tables = $table[0];
		}
		$where = $options['where'] ? $options['where'] : 1;
		$result = @mysqli_query($this->_link,"SELECT count(*) FROM $tables WHERE $where");
    	$count = @mysqli_fetch_row($result);
    	if(mysqli_errno($this->_link)){
			$this->writelog('数据获取count(*)错误:'.mysqli_error($this->_link));
		}
    	return $count[0];
	}

	// 关闭数据库

	public function close(){
    	mysqli_close($this->_link);
	}
}